$(function(){
	App.page = '#';
	App.scheme = 'basic';
	
	var pg = $('body'), hd = $('#head'), inbox = App.inbox = $('#inbox'),
		lg = hd.children('.logon'), bd = App.body = $('#body'),
		left = App.left = $('#left') , main = App.main = $('#main');
	App.inits = [];

	if (App.getHashParam('token')) {
		hd.hide();
	}
	
	function login() {
		App.popup({
			ctx: 'auth',
			action: 'sysLogin',
			title: '用户登录',
			model: true,
			noCloser: true,
			params: { type: 1 }
		}, function(uo, w){
			//hd.show();
			//left.show();
			//bd.height(pg.height() - hd.height());
			init(uo, w);
		});
	}

	function logout(){
		$.get(App.auth.ctx + '/sys/user/logout.do', {
		}, function(){
			window.location.href = App.ctx;
		});
	}

	App.go = function(to) {
		if (!App.logon) {
			login();
			return;
		}
		App.page = to;
		if (window.location.hash != to) {
			window.location.hash = to;
		}
		var i = to.indexOf('?');
		if (i > 0) {
			to = to.substr(0, i);
		}
		App.go2(to);
		//window.history.pushState('forward', null, './#forward');
	}
	
	App.navi = function(pg){
		pg.children('.navi').find('span.a').click(function(){
			var a = $(this).attr('name');
			App.show({
				ctx: App.code,
				action: a
			}, $.noop, App.main);
		});
	}

	function adjust(){
		var de = document.documentElement
			, ch = de.clientHeight, cw = de.clientWidth
			, h = hd.height(), w = cw;
		h = ch - h - 2;
		bd.width(w).height(h);
		//bd.height(pg.height() - hd.height());
		left.height(h);
		w = left.is(':visible')? left.width():0;
		main.height(h).width(cw - w - 1);
	}
	$(window).resize(adjust);
	adjust();

	if (window.history && window.history.pushState) {
		window.onpopstate = function() {
			if (App.page != window.location.hash) {
				App.go(window.location.hash);
			}
		}
	}

	hd.find('span.a[name]').click(function(){
		var a = $(this).attr('name');
		switch(a){
		case 'login':
			login();
			break;
		case 'logout':
			logout();
			break;
		case 'password':
			App.open({
				ctx: 'auth',
				action: 'setpwd',
				params: App.logon,
				model: true
			}, function(){
				//
			});
			break;
		}
	});
	
	hd.find('.leftBtn').click(function(){
		var a = $(this);
		a.toggleClass('on');
		left.toggle(a.hasClass('on'));
		$(window).trigger('resize');
	});

	function accordin() {
		var funcs = $.map(App.logon.funcs, function(f){
			if (f.type && f.type.indexOf('main.menu') == 0) {
				return f;
			}
		}).sort(function(a, b){
			if (a.type == b.type) {
				return a.no - b.no;
			}
			return a.type > b.type;
		});
		left.empty();
		$.each(funcs, function(n, f){
			var ca = f.code.split('.'), ap = left, lv = ca.length,
				mc = ca[lv - 1], cx = ca[0], fa = f.type.split('.'),
				cp = $('<div class="' + mc + ' menu' + lv + '"></div>'),
				flag = App[cx] && App[cx][mc];
			//
			if (fa.length > 2) {
				ca[0] = fa[fa.length - 1];
			}
			if (lv > 1) {
				ap = ap.find('div.' + ca.slice(0, -1).join('>.') + '>.body');
			}
			if (ap.children('.' + mc).length < 1) {
				ap.append(cp);
			}
			var wl = window.location, p = wl.port, uri;
			if (f.uri) {
				if (f.uri.substr(4) == 'http') {
					uri = f.uri;
				} else {
					uri = wl.protocol + '//' + wl.host
						+ (p? (':' + p) : '') + '/' + f.uri;
				}
			} else {
				uri = wl.protocol + '//' + wl.host
					+ (p? (':' + p) : '') + '/' + cx + '#' + mc;
			}
			var hd = $('<div class="head"></div>').click(function(){
				var me = $(this), n = me.next();
				if (n.html()) {
					if (me.hasClass('open')) {
						me.removeClass('open');
						n.hide();
					} else {
						me.addClass('open');
						n.show();
					}
				} else if (lv > 1) {
					if (flag) {
						App.show({
							ctx: cx,
							action: mc
						}, null, main);
					} else {
						window.location = uri;
					}
				}
				return false;
			}).appendTo(cp);
			//
			hd.append('<div class="square fl"><span class="icon"></span></div>');
			//
			if (f.uri && !flag) {
				$('<span class="a"></span>').click(function(){
					window.location = uri;
					return false;
				}).append(f.name).appendTo(hd);
				$('<span class="fr"></span>').click(function(){
					window.open(uri);
					return false;
				}).append('<span class="icon icon-newwin"></span>').appendTo(hd);
			} else {
				hd.append(f.name);
			}
			hd.append('<div class="square fr"><span class="icon"></span></div>')
			$('<div class="body"></div>').appendTo(cp);
		});
	}
	
	function topMenu() {
		//
		var mainMenu = hd.children('.mainMenu').mac('menu', {
			children: $.map([{
				title: '首页',
				action: 'home',
				code: 'sys.home',
				icon: 'icon-disk'
			},{
				title: '系统环境管理',
				action: 'envIndex',
				code: 'env.list',
				icon: 'icon-disk'
			},{
				title: '系统参数配置',
				action: 'sysParamIndex',
				code: 'sys.param.list',
				icon: 'icon-disk'
			},{
				title: '系统模块管理',
				action: 'sysFuncIndex',
				code: 'sys.func.list',
				icon: 'icon-disk'
			},{
				title: '系统角色管理',
				action: 'sysRoleIndex',
				code: 'sys.role.list',
				icon: 'icon-disk'
			},{
				title: '系统用户管理',
				action: 'sysUserIndex',
				code: 'sys.user.list',
				icon: 'icon-disk'
			}], function(a){
				if (App.logon.power(a.code)) {
					return a;
				}
			})
		}).appendTo(pg);
		
		hd.find('.menuBtn').contextMenu({
			menu: mainMenu,
			button: 1,
			anchor: 'el',
			offset: { x: 4, y: 60 }
		}, function(act, el, pos) {
			switch (act) {
				case 'envIndex':
					App.show({
						ctx: 'base',
						action: 'envIndex',
						title: '环境管理',
						params: {}
					}, $.noop, main);
					break;
				case 'sysParamIndex':
					App.show({
						ctx: 'sys',
						action: 'paramIndex',
						title: '系统参数管理',
						params: {}
					}, $.noop, main);
					break;
				case 'sysFuncIndex':
					App.show({
						ctx : 'auth',
						action: 'sysFuncIndex',
						title : '系统模块管理',
						params : {}
					}, $.noop, main);
					break;
				case 'sysRoleIndex':
					App.show({
						ctx : 'auth',
						action: 'sysRoleIndex',
						title : '系统角色管理',
						params : {}
					}, $.noop, main);
					break;
				case 'sysUserIndex':
					App.show({
						ctx : 'auth',
						action: 'sysUserIndex',
						title : '系统用户管理',
						params : {}
					}, $.noop, main);
					break;
				case 'home':
					App.show({
						ctx : 'batch',
						action: 'home',
						title : '首页',
						params : {}
					}, $.noop);
					break;
			}
			return false;
		}).show();
	}

	function init(uo, w){
		App.logon = uo;
		App.logon.power = function (t){
			var fa = uo.funcs;
			for (var i in fa){ 
				if (fa[i].code == t) {
					return true;
				}
			}
		}

		lg.seek("test").show();
		lg.seek('name').text('当前用户：' + App.logon.name).show();
		lg.seek('reg').hide();
		lg.seek('login').hide();
		lg.seek('logout').show();
		lg.seek('password').show();
		
		topMenu();
		accordin();
		
		if (App.page != window.location.hash) {
			App.go(window.location.hash);
		}
		if (w) {
			w.close();
		}
		
//		App.websocket.open({
	// 		onopen : {
	// 			'fn1' : function(e) {
	// 			}
	// 		},
	// 		onclose : {
	// 			'fn1' : function(e) {
	// 			}
	// 		},
	// 		onerror : {
	// 			'e1' : function(e) {
	// 				alert('websocket出现异常');
	// 			}
	// 		},
//			base: {
//				open: {
//					common: function(o, e, ws){
//						// pg.sessionId = o.data;
//						App.websocket.sessionId = o.data;
//					}
//				}
//			}
//		});
		
		$.each(App.inits, function(i, n){
			n();
		});
	}

	if (!App.logon) {
		if (App.getHashParam('token') || $.cookie('token')) {
			var w = mac.wait('Loading...')
			$.post(App.auth.ctx + '/sys/power/check.do', {
			// $.get('/data.js', {
				r: new Date().getTime()
			}, function(rs){
				var ro = mac.eval(rs);
				if (ro.success) {
					init(ro.data, w);
				} else {
					w.close();
					login();
				}
			});
		} else {
			login();
//			$.get('/data.json', {
//				r: new Date().getTime()
//			}, function(rs){
//				var ro = mac.eval(rs);
//				if (ro.success) {
//					init(ro.data, w);
//				} else {
//					w.close();
//					login();
//				}
//			});
		}
	}
});
